package ooday04;

//多态的实际应用
//1）将不同对象（狗、鱼、鸡）统一封装到一个数组中来访问，实现代码复用
// 2）将超类型作为参数或返回值类型,传递或返回派生类对象，以扩大方法的应用范围，实现代码复用
public class Test {
    public static void main(String[] args) {
        //演示向上造型（多态）的第2点应用
        /*
        Master master = new Master();
        Dog dog = new Dog("小黑", 2, "黑");
        Fish fish = new Fish("小金", 1, "金");
        Chick chick = new Chick("小白", 3, "白");
        master.feed(dog);//在传参的同时，系统自动做了向上造型
        master.feed(fish);
        master.feed(chick);








        /*
        演示多态的第一点应用
         */
        Animal[] animals = new Animal[5];
        animals[0] = new Dog("小黑", 2, "黑");
        animals[1] = new Dog("小白", 3, "白");
        animals[2] = new Fish("小金", 1, "金");
        animals[3] = new Fish("小花", 2, "花");
        animals[4] = new Chick("小灰", 3, "灰");
        for (int i = 0; i < animals.length; i++) {
            System.out.println(animals[i].name);
            animals[i].eat();
            animals[i].drink();
            if(animals[i] instanceof Dog){
                Dog dog=(Dog)animals[i];
                dog.lookHome();
            }
            if(animals[i] instanceof Chick){
                Chick chick=(Chick) animals[i];
                chick.layEggs();
            }
            if(animals[i] instanceof Swim){
                Swim s=(Swim) animals[i];
                s.swim();
            }
        }
        //引用所指向的对象，就是该类型
        //引用所指向的对象，实现了该了该接口或继承了该类
        Animal o=new Dog("小黑",2,"黑");
        Dog d=(Dog)o;
        Swim s=(Swim)o;
        //Fish f=(Fish)o;//运行时会发生ClassCastException错误
        System.out.println(o instanceof Dog);
        System.out.println(o instanceof Swim);
        System.out.println(o instanceof Fish);


        //三个for 循环在重复，因为数据分装在了3个数组中，所以需要3个for循环
        //若将数据统一装在1个数组中，则仅需要一个for就行
        /*
        Dog[] dogs=new Dog[3];
        dogs[0]=new Dog("xa",1,"a");
        dogs[1]=new Dog("xb",2,"b");
        dogs[2]=new Dog("xc",3,"c");
        System.out.println(dogs[0].name);
        dogs[1].age=4;
        for(int i=0;i<dogs.length;i++){
            System.out.println(dogs[i].age);
            dogs[i].drink();
        }
        dogs[2].swim();
        System.out.println();

        Chick[] chicks=new Chick[2];
        chicks[0]=new Chick("xd",1,"d");
        chicks[1]=new Chick("xe",3,"e");
        for(int i=0;i<chicks.length;i++){
            System.out.println(chicks[i].name);
            chicks[i].eat();
        }
        System.out.println();

        Fish[] fish=new Fish[4];
        fish[0]=new Fish("za",1,"a");
        fish[1]=new Fish("zb",3,"b");
        fish[2]=new Fish("zc",2,"c");
        fish[3]=new Fish("zd",4,"d");
        for(int i=0;i<fish.length;i++){
            System.out.println(fish[i].color);
            fish[i].drink();
        }

         */
    }
}
